<template>
    <div class="simple-kline" id="kline-panel-simple">
        <div class="timeshareblock">
            <button  class="btn" :class="{'btn_choosed':timeType=='1m'}" @click="chooseTime('1m')">1M</button>
            <button  class="btn" :class="{'btn_choosed':timeType=='5m'}" @click="chooseTime('5m')">5M</button>
            <button  class="btn" :class="{'btn_choosed':timeType=='15m'}" @click="chooseTime('15m')">15M</button>
            <button  class="btn" :class="{'btn_choosed':timeType=='30m'}" @click="chooseTime('30m')">30M</button>
            <button  class="btn" :class="{'btn_choosed':timeType=='1h'}" @click="chooseTime('1h')">60M</button>
            <button  class="btn" :class="{'btn_choosed':timeType=='1d'}" @click="chooseTime('1d')">1D</button>
        </div>
        <div id="container" :style="{ height: height-39 + 'px' }"></div>
    </div>
</template>

<script type="text/babel">
    import commonService from '../common/commonService';
    import {LANG, LOCAL,PRECISION} from '../util/lang';
    import filter from '../util/filter';
    import lib from '../../src/common/lib'

    export default {
        components: {

        },
        props:{
            wsSymbol:{
                default:'BTC_ETH'
            },
            height:{
                default:400
            }
        },
        data() {
            return {
                filter:filter,
                timeType:'5m',
                ohlc:[],
                volume:[],
                myCharts:'',
                dataMax:[],
                dataMin:[],

                oChart : null
            };
        },

        created() {
            this.fetchKlineData();

        },
        mounted(){

        },
        methods: {

            chooseTime(time){
                this.timeType = time;
                this.oChart&&this.oChart.showLoading();
                this.fetchKlineData();
            },


            fetchKlineData(){
                let param = {
                    symbol:this.wsSymbol,
                    kline:this.timeType
                };
                commonService.kline(param).then((rep) => {
                    let klineData = [];
                    if(_.isArray(rep) && rep.length>0){
                        klineData = rep.reverse();
                    }


                    //获取数据后 重新绘制图像
                    let ohlc = [];
                    let volume = [];
                    let len =  klineData.length;
//                    if(len>=90){
//                        klineData = klineData.slice(0,90);
//                        len =  klineData.length;
//                    }

                    for(let i = 0;i<len;i++){
                        if(klineData[i].time === 0){
                            continue;
                        }
                        ohlc.push([
                            klineData[i].time*1000,
                            klineData[i].open,
                            klineData[i].maxPrice,
                            klineData[i].lowPrice,
                            klineData[i].close
                        ]);
                        volume.push([
                            klineData[i].time*1000,
                            klineData[i].amount
                        ]);

                    }
                    this.ohlc = ohlc;
                    this.volume = volume;
                    this.dataMax = _.maxBy(ohlc,2);
                    this.dataMin = _.minBy(ohlc,3);
                    if( this.dataMax&&this.dataMin&&(this.dataMax[0]===this.dataMin[0])){
                        this.dataMin = [];
                    }

                    this.highcharts_Rendering();


                }).fail((rep) => {

                }).always(()=> {

                });
            },


            highcharts_Rendering() {
                let that = this;
                let line_options = {
                    loading: {
                        style: {
                            position: 'absolute',
                            opacity: 0.2,
                            textAlign: 'center',
                            backgroundColor: 'none',
                            background: 'url("../img/loading-2.gif") center center no-repeat',//显示的背景动态gif图片，设置此项为gif图片即可实现常见的加载中动态效果图
                            backgroundSize: '32px 32px',//设置背景图片铺满Series数据列区域
                            fontSize:0
                        }
                    },
                    credits: {enabled: false},
                    chart: {renderTo: 'container', backgroundColor: '#212121',  spacing: [24, 16, 8, 16]},
                    xAxis: {
                        type: 'datetime',
                        lineWidth: 1,
                        lineColor:'#343535',
                        tickLength: 1,
                        labels: {
                            style: {color: '#8c8c8c'}
                        },
                        crosshair: {color: 'rgba(80,94,102,0.15)',width:6},
                        dateTimeLabelFormats: {
                            minute: '%H:%M',
                            hour: '%H:%M',
                            day: '%m-%d'
                        }

                    },
                    legend: {enabled: false},
                    scrollbar: {enabled: false},
                    navigator: {enabled: false},
                    rangeSelector: {enabled: false},
                    tooltip: {
                        useHTML: true,
                        shared: true,
                        positioner: function () {
                            return {x: 0,y:-8};
                        },
                        formatter: function () {
                            let pots = this.points;

                            let zdf;
                            let nowPrice;
                            let prevPrice;
                            let cls = '#d13415';
                            if (!pots || !pots.length) return;

                            //高开收低
                            let point = pots[0].point;
                            let open = point.open;
                            let high = point.high;
                            let low = point.low;
                            let close = point.close;
                            let time = pots[0].x;


                            for (let i = 0; i < that.ohlc.length; i++) {
                                if ((time == that.ohlc[i][0])) {
                                    if (i > 0) {
                                        prevPrice = that.ohlc[i - 1][4];
                                        nowPrice = that.ohlc[i][4];
                                        zdf = (nowPrice - prevPrice) / nowPrice * 100;
                                    } else {
                                        zdf = 0;
                                    }
                                    break;
                                };
                            };

                            zdf = filter.floorFix(zdf, 2);

                            if (parseFloat(zdf) >= 0) {
                                zdf = '+' + zdf;
                                cls = '#17a21d';
                            };

                            let volume = pots[1]?filter.fix(pots[1].y, that.$$amountPrecision):0.0000;//成交量

                            let tips = '<p style="line-height:25px;"><span style="color:#8c8c8c;font-size:12px;">' + Highcharts.dateFormat('%Y-%m-%d %H:%M', time) +'</span>&emsp;';
                            tips += '<span style="color:#8c8c8c;font-size:12px;">Open:' + filter.floorFixPrice(open, that.$$coinPrecision) + '</span>&emsp;';
                            tips += '<span style="color:#8c8c8c;font-size:12px;">High:' + filter.floorFixPrice(high, that.$$coinPrecision) + '</span>&emsp;';
                            tips += '<span style="color:#8c8c8c;font-size:12px;">Low:' + filter.floorFixPrice(low, that.$$coinPrecision) + '</span>&emsp;';
                            tips += '<span style="color:#8c8c8c;font-size:12px;">Close:' + filter.floorFixPrice(close, that.$$coinPrecision) + '</span>&emsp;';
                            tips += '<span style="color:#8c8c8c;font-size:12px;word-wrap:break-word">Chg:<strong style="color:'+cls+'">' + zdf + '%</strong></span>&emsp;';
                            tips += '<span style="color:#8c8c8c;font-size:12px;">Volume:' + volume + '</span>&emsp;';


                            tips += '</p>';
                            return tips;
                        },
                        color: '#4a596b',
                        shadow: false,
                        borderWidth: 0,
                        backgroundColor: 'none'
                    },
                    yAxis: [
                        {
                            top:'5%',
                            height: '70%',
                            labels: {
                                style: {color: '#8c8c8c'},
                                formatter: function () {
                                    return filter.floorFixPrice(this.value, that.$$coinPrecision);
                                }
                            },
                            title: {
                                text: that.$t('common.comp.price')+'('+that.wsSymbol.split('_')[0]+')',
                                style: {color: '#8c8c8c'}
                            },
                            gridLineWidth: 1,
                            gridLineDashStyle:'ShortDash',
                            gridLineColor:'#343535',
                            opposite:false,
                            crosshair: {color: '#6e8895', zIndex: 99,dashStyle:'ShortDash'},

                        },//价格
                        {
                            top: '75%',
                            height: '25%',
                            labels: {style: {color: '#8c8c8c'}},
                            title: {text: null, style: {color: '#4a596b'}},
                            gridLineWidth: 0,
                            offset:24,
                            opposite:true,
                            gridLineColor:'transparent',
                            plotBands: [{
                                from:-99999,
                                to:99999,
                                color: '#1a1a1a'
                            }]
                        },//成交量
                    ],
                    plotOptions: {
                        spline:{
                            color:'transparent',
                            lineWidth:1,
                            states:{
                                hover:{
                                    lineWidth:1
                                }
                            },
                            marker:{
                                radius:0,
                            }
                        }
                    },

                    series:[
                        {
                            name: '价格',
                            type: 'candlestick',
                            id:'ohlcSeries',
                            lineWidth:2,
                            color: '#d13415',
                            lineColor: '#d13415',
                            upColor: '#212121',
                            upLineColor: '#17a21d',
                            data: this.ohlc,
                            maxPointWidth:4
                        },
                        {
                            animation: true,
                            name: '成交量',
                            type: 'column',
                            yAxis: 1,
                            data: this.volume,
                            maxPointWidth:8
                        },
                        {
                            type : 'flags',
                            onSeries:'ohlcSeries',
                            color: '#fff',
                            data:[
                                {
                                    fillColor:'transparent',
                                    title:filter.floorFixPrice(that.dataMax[2], that.$$coinPrecision),
                                    x:that.dataMax[0]?that.dataMax[0]:null
                                },
                                {
                                    fillColor:'transparent',
                                    title:filter.floorFixPrice(that.dataMin[3], that.$$coinPrecision),
                                    x:that.dataMin[0]?that.dataMin[0]:null
                                }
                            ],
                            style:{
                                fontSize: '11px',
                                fontWeight: 'normal',
                                textAlign: 'center',
                                border:0,
                                color: '#fff',
                            },
                            shape:'url(../img/line.png)'
                        }
                    ]
                };


                Highcharts.setOptions({global: {useUTC: true,timezoneOffset:lib.getCurrentTimezone()*60}})
                this.oChart = new Highcharts.StockChart(line_options);

                this.oChart.hideLoading();
            }
        }
    }

</script>

<style lang="sass" rel="stylesheet/scss">
    $color-link: #0b95ff;
    .btn{
        font-size: 12px;
        background-color: #2f3235;
        border-radius: 2px;
        padding: 4px 8px;
        color:#8c8c8c;
        margin-right:8px ;
    }

    .btn_choosed{
        background-color: #181a1c;
        color:#fff;
    }

    .timeshareblock{
        background-color: #212121;
        box-sizing: border-box;
        color:#8c8c8c;
        padding: 8px;
    }

    .line-label{
        border-radius: 50%;
        width: 2px;
    }

</style>